package com.ruoyi.web.controller.business.order;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruoyi.business.base.PageParam;
import com.ruoyi.business.order.domain.JbApprovalLog;
import com.ruoyi.business.order.domain.JbOrder;
import com.ruoyi.business.order.service.JbOrderService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.web.controller.business.audit.factory.JbAuditFactory;
import com.ruoyi.web.controller.business.order.factory.JbOrderFactory;
import com.ruoyi.web.controller.business.order.vo.JbAuditVO;
import com.ruoyi.web.controller.business.order.vo.JbOrderVO;
import com.ruoyi.web.controller.thirdparty.factory.ThirdpartyExtendFactory;
import com.ruoyi.web.core.JoController;
import com.ruoyi.web.core.JoR;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * 订单 Controller
 *
 * @author ruoyi
 * @date 2024-10-11
 */
@Api("订单")
@RestController
@RequestMapping("/order")
public class JbOrderController extends JoController
{
    private static final Logger log = LoggerFactory.getLogger(JbOrderController.class);

    @Autowired
    private JbOrderService service;

    @Autowired
    private JbOrderFactory jbOrderFactory;
    @Autowired
    private JbAuditFactory jbAuditFactory;
    @Autowired
    private ThirdpartyExtendFactory thirdpartyExtendFactory;

    /**
     * 查询订单列表
     */
    @ApiOperation("查询订单列表")
    @PreAuthorize("@ss.hasPermi('order:list')")
    @GetMapping("/list")
    public TableDataInfo list(PageParam page, JbOrder jbOrder)
    {
        return JoR.rows(jbOrderFactory.list(page, jbOrder));
    }

    /**
     * 导出订单列表
     */
    @ApiOperation("导出订单列表")
    @PreAuthorize("@ss.hasPermi('order:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PageParam page, JbOrder jbOrder)
    {
        LambdaQueryWrapper<JbOrder> select = new LambdaQueryWrapper<>();
        IPage<JbOrder> iPage = service.page(page.b(), select);

        List<JbOrder> list = iPage.getRecords();
        ExcelUtil<JbOrder> util = new ExcelUtil<JbOrder>(JbOrder.class);
        util.exportExcel(response, list, "订单数据");
    }

    /**
     * 获取订单详细信息
     */
    @ApiOperation("获取订单详细信息")
    @PreAuthorize("@ss.hasPermi('order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(jbOrderFactory.getInfo(id));
    }

    /**
     * 获取订单详细信息
     */
    @ApiOperation("获取订单详细信息")
    @PreAuthorize("@ss.hasPermi('order:query')")
    @GetMapping(value = "/number/{number}")
    public AjaxResult getInfoByNumber(@PathVariable("number") String number)
    {
        return success(jbOrderFactory.getInfoByNumber(number));
    }

    /**
     * 新增订单草稿
     */
    @ApiOperation("新增订单草稿")
    @PreAuthorize("@ss.hasPermi('order:draft')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("/draft")
    public AjaxResult draft(@RequestBody JbOrderVO jbOrderVO)
    {
        //下单前 校验金额
        if (jbOrderVO.getCommodityList().isEmpty()) return AjaxResult.error("订单商品数据异常");
        try
        {
            return toAjax(jbOrderFactory.draft(jbOrderVO));
        } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e)
        {
            log.error(e.getMessage());
            return error("保存失败");
        }
    }

    /**
     * 新增订单
     */
    @ApiOperation("新增订单")
    @PreAuthorize("@ss.hasPermi('order:add,allOrder:add,examineOrder:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody JbOrderVO jbOrderVO)
    {
        //下单前 校验金额
        if (jbOrderVO.getCommodityList().isEmpty()) return AjaxResult.error("订单商品数据异常");
        try
        {
            return toAjax(jbOrderFactory.add(jbOrderVO));
        } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e)
        {
            log.error(e.getMessage());
            return error("新建失败");
        }
    }

    /**
     * 置顶
     */
    @ApiOperation("置顶")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping("/top")
    public AjaxResult top(@RequestBody JbOrderVO jbOrderVO)
    {
        return toAjax(jbOrderFactory.top(jbOrderVO));
    }

    /**
     * 取消置顶
     */
    @ApiOperation("取消置顶")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping("/unTop")
    public AjaxResult unTop(@RequestBody JbOrderVO jbOrderVO)
    {
        return toAjax(jbOrderFactory.unTop(jbOrderVO));
    }

    /**
     * 作废
     */
    @ApiOperation("作废")
    @PreAuthorize("@ss.hasPermi('order:to_void')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping("/toVoid")
    public AjaxResult toVoid(@RequestBody JbOrderVO jbOrderVO)
    {
        return toAjax(jbOrderFactory.toVoid(jbOrderVO));
    }

    /**
     * 结束
     */
    @ApiOperation("结束")
    @PreAuthorize("@ss.hasPermi('order:end')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping("/end")
    public AjaxResult end(@RequestBody JbApprovalLog jbApprovalLog)
    {
        return toAjax(jbOrderFactory.end(jbApprovalLog));
    }

    /**
     * 修改订单
     */
    @ApiOperation("修改订单")
    @PreAuthorize("@ss.hasPermi('order:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody JbOrderVO jbOrderVO)
    {
        //下单前 校验金额
        if (jbOrderVO.getCommodityList().isEmpty()) return AjaxResult.error("订单商品数据异常");
        try
        {
            return toAjax(jbOrderFactory.edit(jbOrderVO));
        } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e)
        {
            log.error(e.getMessage());
            return error("保存失败");
        }
    }

    /**
     * 删除订单
     */
    @ApiOperation("删除订单")
    @PreAuthorize("@ss.hasPermi('order:remove')")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(jbOrderFactory.remove(ids));
    }

    /**
     * 创建用友 销售订单
     */
    @ApiOperation("销售订单")
    @PostMapping("/tCreate")
    public AjaxResult tCreate(@RequestBody JbAuditVO jbAuditVO)
    {
        JbOrder jbOrder = service.getOne(new LambdaQueryWrapper<JbOrder>().eq(JbOrder::getOrderNumber,
                jbAuditVO.getBusinessCode()));
        jbAuditFactory.fnOrderFinance(jbAuditVO, jbOrder);
        return JoR.success();
    }

    /**
     * 查询 发货信息
     *
     * @param jbOrder
     * @return
     */
    @ApiOperation("查询 发货信息")
    @PostMapping("/listShippingInformation")
    public AjaxResult listShippingInformation(JbOrder jbOrder)
    {
        return JoR.success(thirdpartyExtendFactory.listShippingInformation(jbOrder.getOrderNumber()));
    }

    /**
     * 计算商品信息
     */
    @ApiOperation("计算商品信息")
    @PostMapping("/fnCommodity")
    public AjaxResult fnCommodity(@Valid @RequestBody JbOrderVO jbOrderVO)
    {
        jbOrderFactory.fnPriceType(jbOrderVO);
        return JoR.success(jbOrderVO);
    }

    /**
     * 计算商品信息
     */
    @ApiOperation("计算商品信息")
    @GetMapping("/findProcess")
    public AjaxResult findProcess(String processId)
    {
        JSONObject jsonObject = service.findProcess(processId);
        if (ObjectUtil.isEmpty(jsonObject))
        {
            throw new ServiceException("当前订单还未发起流程,请提交后再查看");
        }
        return JoR.success(jsonObject);
    }

}
